package linklist;

import org.junit.Test;

/*
 *@description
 *@author hkfan
 *@version 1.0
 *@create 2025/6/10 10:39
 */
public class LeetCode_25 {
    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    @Test
    public void test(){
        reverseKGroup(new ListNode(1,new ListNode(2,new ListNode(3,new ListNode(4,new ListNode(5,null))))),2);

    }

    public ListNode reverseKGroup(ListNode head, int k) {
        //0. 特殊
        if (k<=1 || head==null ||head.next==null){
            return head;
        }
        //1. 计算长度
        int len=1;
        ListNode p = head,tempHead=new ListNode(0,head);
        while (p.next!=null){
            p=p.next;
            len++;
        }
        //2. 循环
        p=tempHead;
        for (int i = 0; i < len/k; i++) {
            ListNode res = reverse(p,k);
            p = res;
        }
        return tempHead.next;

    }

    private ListNode reverse(ListNode preStart, int k) {
        ListNode p = preStart.next,q=p.next;
        ListNode res = preStart.next;
        int i=1;

        while (i<k){
            ListNode temp = q.next;
            q.next = p;
            p=q;
            q=temp;
            i++;
        }
        res.next = q;
        preStart.next=p;

        return res;
    }




}
